QT对socket作了简单的封装,使得在Windows和Linux下都可以用相同的上层代码来写,不需要关心底层的实现.本文示例的是使用UDP协议进行的通信.
运行效果:

核心代码
server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include "receiver.h" #include "ui_receiver.h" #include <QDebug> Receiver::Receiver(QWidget *parent) : QDialog(parent), ui( new Ui::Receiver) { ui->setupUi( this ); sock = new QUdpSocket( this ); sock->bind(6666); connect(sock, SIGNAL(readyRead()), this , SLOT(processPendingDatagrams())); } Receiver::~Receiver() { delete ui; } void Receiver::processPendingDatagrams() { while (sock->hasPendingDatagrams()){ QByteArray data; data.resize(sock->pendingDatagramSize()); sock->readDatagram(data.data(), data.size()); ui->plainTextEdit->appendPlainText(data.data()); } } |
client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include "sender.h" #include "ui_sender.h" #include <QtNetwork> sender::sender(QWidget *parent) : QDialog(parent), ui( new Ui::sender) { ui->setupUi( this ); ui->plainTextEdit->setReadOnly( true ); sock = new QUdpSocket( this ); } sender::~sender() { delete ui; } void sender::on_pushButton_clicked() { QByteArray data(ui->lineEdit->text().toStdString().c_str()); sock->writeDatagram(data.data(), data.size(), QHostAddress::LocalHost, 6666); ui->plainTextEdit->appendPlainText(data.data()); } |